/* storage.js */

const storage = {
  get(key, cb) {
    let value = window.localStorage.getItem(key) || ''
    if (!value) {
      return value
    }
    cb = cb || function() {
    }
    let type = value.split('_')[0]
    let res = value.match(/_([\s\S]*)/)[1]
    if (type === 'array' || type === 'object') {
      res = JSON.parse(res)
    }
    if (type === 'boolean') {
      res = Boolean(res)
    }
    if (type === 'number') {
      res = Number(res)
    }
    cb(null, res)
    return res
  },
  set(key, value, cb) {
    value = value || ''
    if (!value) {
      return
    }

    cb = cb || function() {
    }
    if (Array.isArray(value)) {
      window.localStorage.setItem(`${key}`, `arrya_${JSON.stringify(value)}`)
    }
    if (typeof value === 'object') {
      window.localStorage.setItem(`${key}`, `object_${JSON.stringify(value)}`)
    }
    if (typeof value === 'string') {
      window.localStorage.setItem(`${key}`, `string_${value}`)
    }
    if (typeof value === 'boolean') {
      window.localStorage.setItem(`${key}`, `boolean_${value}`)
    }
    if (typeof value === 'number') {
      window.localStorage.setItem(`${key}`, `number_${value}`)
    }
    cb()
    return value
  },
  remove(key, cb) {
    cb = cb || function() {
    }
    window.localStorage.removeItem(key)
    cb()
  },
  clear: function(cb) {
    window.localStorage.clear()
    cb && cb()
  }
}
window.storage = storage
export default storage
